// pages/profile/profile.js
Page({
  data: {
    currentTab: 'profile',
    userInfo: {
      avatarUrl: '/pages/profile/default-avatar.png',
      nickName: '用户',
      gender: 0,
      age: 30,
      height: 170,
      weight: 65
    },
    hasUserInfo: false,
    canIUseGetUserProfile: false,
    sleepStatistics: {
      totalSleepDays: 120,
      averageScore: 82,
      averageDuration: '7小时15分钟',
      bestScore: 95
    },
    deviceInfo: {
      deviceName: '智能枕头 Pro',
      deviceId: 'SP12345678',
      firmwareVersion: 'v2.1.0',
      batteryLevel: 85,
      lastConnected: '2025-05-08 08:30'
    }
  },

  onLoad: function (options) {
    // 页面加载时执行，获取用户信息
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      });
    }
    
    const app = getApp();
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      });
    } else if (app.userInfoReadyCallback) {
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        });
      };
    }
  },

  onShow: function () {
    if (typeof this.getTabBar === 'function' &&
        this.getTabBar()) {
      this.getTabBar().setData({
        selected: this.data.currentTab
      })
    }
  },
  getUserProfile: function() {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    wx.getUserProfile({
      desc: '用于完善用户资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中
      success: (res) => {
        const app = getApp();
        app.globalData.userInfo = res.userInfo;
        
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        });
      }
    });
  },
  myProfileFn(){
    this.triggerEvent('myProfileFn');
  },
  navigateToSettings: function() {
    wx.showToast({
      title: '设置功能开发中',
      icon: 'none'
    });
  },

  navigateToHelp: function() {
    wx.showToast({
      title: '帮助功能开发中',
      icon: 'none'
    });
  },

  navigateToAbout: function() {
    wx.showToast({
      title: '关于功能开发中',
      icon: 'none'
    });
  },

  navigateToFeedback: function() {
    wx.showToast({
      title: '反馈功能开发中',
      icon: 'none'
    });
  },

  handleTabChange: function(event) {
    console.log('handleTabChange called:', event.detail); // 添加日志

    const { value } = event.detail;
    if (value !== this.data.currentTab) {
      wx.switchTab({
        url: `../${value}/${value}`
      });
    }
  }
});
